package com.ovopark.organize.server.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.util.StringUtil;
import com.ovopark.organize.server.mapper.FranchiseesRegistrationFieldMapper;
import com.ovopark.organize.server.model.entity.FranchiseesRegistrationField;
import com.ovopark.organize.server.model.entity.FranchiseesRegistrationFieldSelect;
import com.ovopark.organize.server.model.vo.FranchiseesFieldSaveVo;
import com.ovopark.organize.server.model.vo.FranchiseesFieldVo;
import com.ovopark.organize.server.model.vo.FranchiseesRegistrationModuleVo;
import com.ovopark.organize.server.service.FranchiseesRegistrationContentService;
import com.ovopark.organize.server.service.FranchiseesRegistrationFieldSelectService;
import com.ovopark.organize.server.service.FranchiseesRegistrationFieldService;
import com.ovopark.organize.server.util.CollectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FranchiseesRegistrationFieldServiceImpl extends ServiceImpl<FranchiseesRegistrationFieldMapper, FranchiseesRegistrationField> implements FranchiseesRegistrationFieldService {

    Logger logger = LoggerFactory.getLogger(FranchiseesRegistrationFieldServiceImpl.class);
    @Resource
    private FranchiseesRegistrationFieldSelectService franchiseesSelectService;
    @Resource
    private FranchiseesRegistrationContentService franchiseesRegistrationContentService;

    @Resource
    private  MessageSource messageSource;

    @Override
    public List<FranchiseesRegistrationModuleVo> getFranchiseesRegistrationModuleByGroupId(Integer groupId,Locale locale) {

        // 先获取 企业配置的模板 如果没有 获取 默认模板
        List<FranchiseesRegistrationModuleVo> list = baseMapper.getFranchiseesRegistrationModuleByGroupId(groupId);
        if(CollectionUtil.isEmpty(list)){
            // 生成 企业模板
            list = baseMapper.getFranchiseesRegistrationModuleByGroupId(null);
            if(CollectionUtil.isNotEmpty(list)){
                LambdaQueryWrapper<FranchiseesRegistrationField> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.isNull(FranchiseesRegistrationField::getGroupId);
                List<FranchiseesRegistrationField>  fields = baseMapper.selectList(queryWrapper);
                List<Integer> oldFieldIds = new ArrayList<>();
                for (FranchiseesRegistrationField field:fields) {
                    Integer id = field.getId();
                    oldFieldIds.add(id);

                    FranchiseesRegistrationField newField = new FranchiseesRegistrationField();
                    BeanUtils.copyProperties(field,newField);
                    newField.setId(null);
                    newField.setGroupId(groupId);
                    baseMapper.insert(newField);
                    Integer newId = newField.getId();
                    logger.info("企业配置模板生成成功，新模板id01:{},新选项id:{}",id,newId);
                    Integer oldSelectId = null;
                    Integer select = null;
                    if(field.getIsMultiple() !=null && field.getIsMultiple().intValue() ==1){
                        // 多选项的 数据复制
                       List<FranchiseesRegistrationFieldSelect> selects = franchiseesSelectService.getSelectByFieldId(id);
                       if(CollectionUtil.isNotEmpty(selects)){
                           for (FranchiseesRegistrationFieldSelect select1:selects) {
                               oldSelectId = select1.getId();
                               FranchiseesRegistrationFieldSelect newSelectF = new FranchiseesRegistrationFieldSelect();
                               BeanUtils.copyProperties(select1,newSelectF);
                               newSelectF.setId(null);
                               newSelectF.setFranchiseesRegistrationFieldId(newId);
                               newSelectF.setGroupId(groupId);
                               select = franchiseesSelectService.saveOrUpdateFranchiseesRegistrationFieldSelect(newSelectF).getId();
                                 logger.info("企业配置模板生成成功，新模板id:{},新选项id:{}",oldSelectId,select);
                               // 旧数据的 刷新
                               franchiseesRegistrationContentService.updateFieldIdByOldFieldId(id,newId,groupId,oldSelectId,select);
                           }

                       }

                    }else {
                        // 旧数据的 刷新
                        franchiseesRegistrationContentService.updateFieldIdByOldFieldId(id,newId,groupId,oldSelectId,select);
                    }

                }
                list = baseMapper.getFranchiseesRegistrationModuleByGroupId(groupId);
            }

        }
        List<FranchiseesRegistrationModuleVo> result = new ArrayList<>();
        // 聚合
        if(CollectionUtil.isNotEmpty(list)){

            Map<Integer,FranchiseesRegistrationModuleVo> voMap = new HashMap<>();
            for (FranchiseesRegistrationModuleVo vo:list ) {
                Integer id = vo.getId();
                String systemName = vo.getSystemName();
                if(locale !=null && StringUtil.isNotEmpty(systemName)){
                    String name = messageSource.getMessage("franchisees.field."+systemName, null, locale);
                    vo.setFieldName(name);
                }
                if(vo.getIsMultiple() !=null && vo.getIsMultiple().intValue() ==1){
                    FranchiseesRegistrationModuleVo moduleVo =  voMap.get(id);
                    if(moduleVo ==null){
                        moduleVo = vo;
                    }
                    // 多选
                    List<FranchiseesRegistrationFieldSelect> selects  =   moduleVo.getFieldSelectList();
                    if(CollectionUtil.isEmpty(selects)){
                        selects = new ArrayList<>();
                    }
                    FranchiseesRegistrationFieldSelect select = new FranchiseesRegistrationFieldSelect();
                    select.setFranchiseesRegistrationFieldId(vo.getId());
                    select.setId(vo.getSelectId());
                    select.setName(vo.getSelectName());
                    selects.add(select);
                    vo.setFieldSelectList(selects);
                    moduleVo.setFieldSelectList(selects);
                    voMap.put(id,moduleVo);
                }else {
                    result.add(vo);
                }

            }

            if(CollectionUtils.isNotEmpty(voMap)){
                voMap.forEach((k,v)->{
                    result.add(v);
                });
                // 排序
                Collections.sort(result, (o1, o2) -> o1.getIsOrder() - o2.getIsOrder());
            }

        }
        return result;
    }

    @Override
    public void saveFranchiseesField(FranchiseesFieldSaveVo vo, Integer userId) {
         if(vo ==null){
            return;
        }
        Integer groupId = vo.getGroupId();
        List<FranchiseesFieldVo> franchiseesFieldVos = vo.getFranchiseesFieldVos();
        if(CollectionUtil.isEmpty(franchiseesFieldVos)){
            return;
        }

        // 先查询 之前的 企业配置的模板 如果没有 获取 默认模板
        List<FranchiseesRegistrationModuleVo> list = getFranchiseesRegistrationModuleByGroupId(groupId,null);
        Map<Integer,FranchiseesRegistrationModuleVo> moduleVoMap = new HashMap<>();
        List<Integer> ids = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(list)){
            // 删除
            moduleVoMap = list.stream().collect(Collectors.toMap(FranchiseesRegistrationModuleVo::getId, a -> a,(k1,k2)->k1));
            ids = list.stream().map(FranchiseesRegistrationModuleVo::getId).collect(Collectors.toList());
        }
        // 保存
        Integer isOrder = 0;
        for (FranchiseesFieldVo field:franchiseesFieldVos) {
            Integer id = field.getId();
            isOrder++;
            List<Integer> oldSelectIds = new ArrayList<>();
            FranchiseesRegistrationField registrationField = new FranchiseesRegistrationField();
            BeanUtils.copyProperties(field,registrationField);
            registrationField.setIsOrder(isOrder);
            if(id ==null){
                // 新增
               registrationField.setGroupId(groupId);
               baseMapper.insert(registrationField);
                id = registrationField.getId();
            }else {
                // 更新
                ids.remove(id);
                baseMapper.updateById(registrationField);
                FranchiseesRegistrationModuleVo olds = moduleVoMap.get(id);
                if(olds !=null && CollectionUtil.isNotEmpty(olds.getFieldSelectList())){
                   oldSelectIds = olds.getFieldSelectList().stream().map(FranchiseesRegistrationFieldSelect::getId).collect(Collectors.toList());
                }

            }

            List<FranchiseesRegistrationFieldSelect> child = field.getFranchiseesRegistrationFieldSelects();
            if(CollectionUtil.isNotEmpty(child)){
                Integer sort = 0;
                for (FranchiseesRegistrationFieldSelect select:child) {
                    Integer selectId = select.getId();
                    sort++;
                    select.setSort(sort);
                    select.setFranchiseesRegistrationFieldId(id);
                    if(selectId !=null){
                        // 更新
                        oldSelectIds.remove(selectId);
                    }
                    franchiseesSelectService.saveOrUpdateFranchiseesRegistrationFieldSelect(select);
                }

            }

            if(CollectionUtil.isNotEmpty(oldSelectIds)){
                franchiseesSelectService.deleteFranchiseesRegistrationFieldSelectByIds(oldSelectIds);
            }



        }

        if(CollectionUtil.isNotEmpty(ids)){
            deleteFranchiseesField(ids);
        }

    }

    @Override
    public void deleteFranchiseesField(List<Integer> ids) {
        // 清除缓存
        if(CollectionUtil.isEmpty(ids)){
            return;
        }

        List<FranchiseesRegistrationField> fields = baseMapper.selectBatchIds(ids);
        if(CollectionUtil.isNotEmpty(fields)){
           for(FranchiseesRegistrationField field:fields){
               field.setIsDeleted(1);
               baseMapper.updateById(field);
           }
        }
        franchiseesSelectService.deleteFranchiseesRegistrationFieldSelectByFieldIds(ids);

    }

    @Override
    public void deleteFranchiseesFieldByGroupId(Integer groupId) {
        if(groupId ==null){
            return;
        }
        LambdaQueryWrapper<FranchiseesRegistrationField> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(FranchiseesRegistrationField::getGroupId,groupId);
        queryWrapper.eq(FranchiseesRegistrationField::getIsDeleted,0);
        List<FranchiseesRegistrationField> fields  = baseMapper.selectList(queryWrapper);
        if(CollectionUtil.isNotEmpty(fields)){
            List<Integer> ids = fields.stream().map(FranchiseesRegistrationField::getId).collect(Collectors.toList());
            deleteFranchiseesField(ids);
        }
    }

    @Override
    public List<Integer> getFieldIdsByGroupId(Integer groupId) {
        List<Integer> ids = new ArrayList<>();
        LambdaQueryWrapper<FranchiseesRegistrationField> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(FranchiseesRegistrationField::getGroupId,groupId);
        queryWrapper.eq(FranchiseesRegistrationField::getIsDeleted,0);
        List<FranchiseesRegistrationField> fields  = baseMapper.selectList(queryWrapper);
        if(CollectionUtil.isNotEmpty(fields)){
            ids = fields.stream().map(FranchiseesRegistrationField::getId).collect(Collectors.toList());
        }
        return ids;
    }

    @Override
    public List<FranchiseesRegistrationField> getFranchiseesRegistrationSystemFieldByGroupId(Integer groupId) {
        LambdaQueryWrapper<FranchiseesRegistrationField> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(FranchiseesRegistrationField::getGroupId,groupId);
        queryWrapper.eq(FranchiseesRegistrationField::getIsDeleted,0);
        queryWrapper.isNotNull(FranchiseesRegistrationField::getSystemName);
        List<FranchiseesRegistrationField> fields  = baseMapper.selectList(queryWrapper);
        return fields;
    }


}
